<?php
include 'head.php';

if($_POST['leave_comment'] == 1) {
    
    if((int)$_POST['reply_to'] > 0) {
        $reply_to = (int)$_POST['reply_to'];
        header('Content-type: application/json');
    } else {
        $reply_to = 0;
    }
    
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $website = trim($_POST['website']);
    $comment = trim($_POST['comment']);
    $post_id = (int)$_POST['post_id'];
    
    if($post_id > 0) {
        if(mb_strlen($name) < 3) {
            $error['name'] = 'Please fill Name field currectly.';
        } else if(strtolower($name) == 'aleksiev' || strtolower($name) == 'boris aleksiev') {
            $error['name'] = 'You can not use that name.';
        }

        if($email) {
            if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $errorMsg = 'Please enter a valid e-mail address.';
            } else if(strtolower($email) == 'b.aleksiev@gmail.com') {
                $errorMsg = 'You can not use that email.';
            }
        } else {
            $error['email'] = 'Please enter email address.';
        }

        if(mb_strlen($comment) == 0) {
            $error['comment'] = 'Please write a comment.';
        }

        if(!$error) {
            query('INSERT INTO comments (author_name,author_email,author_website,content,post_id,reply_to,time) 
                    VALUES("'.escape($name).'","'.escape($email).'","'.escape($website).'",
                    "'.escape($comment).'",'.$post_id.','.$reply_to.','.time().')');
        } else {
            $_SESSION['errors'] = $error;
        }
    }
    
    if($reply_to > 0) {
        $reply['author_name'] = $name;
        $reply['author_email'] = $email;
        $reply['author_website'] = $website;
        $reply['content'] = $comment;
        $reply['time'] = date('d.m.Y H:i', time());
        
        echo json_encode($reply);
        die;
    } else {
        redirect(getRefPage());
    }
}

if($_GET['id'] && (int)$_GET['id'] > 0) {
    $id = (int)$_GET['id'];

    $post = fetch(query('SELECT * FROM posts WHERE id = '.$id.''));

    $post['tags'] = explode(',', $post['tags']);

    $com = fetchAll(query('SELECT * FROM comments WHERE post_id = '.$id.' AND reply_to = 0 ORDER BY `time` DESC'));
    $replys = fetchAll(query('SELECT * FROM comments WHERE post_id = '.$id.' AND reply_to > 0 ORDER BY `time` DESC'));
    
    foreach($com as $c) {
        $comments[$c['id']] = $c;
    }
    
    foreach($replys as $r) {
        $comments[$r['reply_to']]['replys'][] = $r;
    }
    
    $data['post'] = $post;
    $data['comments'] = $comments;
} else {
    redirect('blog');
}

$widgets = true;
$categories = fetchAll(query('SELECT c.*, (SELECT COUNT(*) FROM posts as p WHERE p.category = c.id) as posts FROM categories as c'));
foreach($categories as $c) {
    $categories[$c['id']] = $c;
}
$data['categories'] = $categories;
$data['tags'] = getTags();

include 'load_smarty.php';
